package kafka;

import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;

public class AuthZkClient {
    public static void main(String[] args) throws Exception {
        CountDownLatch connectedSignal = new CountDownLatch(1);

        // 设置全局安全属性
        System.setProperty("zookeeper.sasl.client", "true");
        System.setProperty("zookeeper.sasl.client.username", "123qweQAZ");
        System.setProperty("zookeeper.sasl.client.password", "123qweQAZ");
        System.setProperty("zookeeper.sasl.client.canonicalize", "false");

        ZooKeeper zk = new ZooKeeper("38.147.171.207:2181", 5000, new Watcher() {
            public void process(WatchedEvent we) {
                if (we.getState() == Event.KeeperState.SyncConnected) {
                    connectedSignal.countDown();
                }
            }
        });

        connectedSignal.await();

        // 添加认证
        zk.addAuthInfo("digest", "123qweQAZ:123qweQAZ".getBytes());

        // 测试操作
        try {
            zk.create("/my-node", "data".getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
            System.out.println("Node created!");
        } catch (Exception e) {
            e.printStackTrace();
        }

        zk.close();
    }
}

